import random
import time
from datetime import datetime

from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

from libs.action import WebDriverAction
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement, KeyCode
from libs.task_helper import TaskHelper
from libs.trade_helper import TradeHelper
from libs.window import AdsWindow

def put_slug(region):
    global need_slug
    if need_slug:
        return
    empty_1_locs = image_tool.find_all_targets('slug_empty.png', region)
    empty_2_locs = image_tool.find_all_targets('slug_empty_2.png', region)
    empty_locs = empty_1_locs + empty_2_locs
    if len(empty_locs) > 0:
        if slug_index is None:
            need_slug = True
            log.debug('need_slug')
            return
        game.use_backpack_item(slug_index)
        current_x = 100
        current_y = 1000
        ac.reset_actions()
        ac.move_by_offset(current_x, current_y).perform()
        for loc in empty_locs:
            x, y = loc
            x = x + 100
            y = y + 70
            ac.move_by_offset(x - current_x, y - current_y).perform()
            current_x = x
            current_y = y
            ac.click().perform()
            time.sleep(0.2)
        ac.reset_actions()
        ac.move_by_offset(100, 1000).perform()

    action.escape()
    return len(empty_locs)


def collect(region):
    ac.reset_actions()
    current_x = 100
    current_y = 1000
    ac.move_by_offset(current_x, current_y).perform()
    ready_locs = image_tool.find_all_targets('slug_ready.png', region)
    for loc in ready_locs:
        x, y = loc
        ac.move_by_offset(x - current_x, y - current_y).perform()
        current_x = x
        current_y = y
        ac.click().perform()
        time.sleep(0.2)

    ac.reset_actions()
    ac.move_by_offset(100, 1000).perform()

    return len(ready_locs)


def move_and_collect():
    log.debug(f'move_up_and_collect')
    top_sign = 'storage_door.png'
    end_sign = 'land_3450_right_arrow.png'

    region = (100, 390, 888, 820)
    stop = False
    see_top = 0
    for _ in range(10):
        # 放蚕
        put_slug(region)

        collect_count = collect(region)
        collect_count += collect(region)
        move_seconds = random.randint(14, 18) / 10
        movement.keep_move_up(move_seconds)
        time.sleep(1)
        if stop:
            break
        if image_tool.find_target(top_sign) is not None:
            if see_top >= 2:
                stop = True
            else:
                see_top += 1

    movement.keep_move_right(4)
    movement.keep_move_right(4)
    for _ in range(10):
        # 放蚕
        if slug_index is not None:
            put_slug(region)
        if game.get_energy() > 350:
            collect_count = collect(region)
            collect_count += collect(region)
        move_seconds = random.randint(14, 18) / 10
        movement.keep_move_down(move_seconds)
        time.sleep(0.5)
        if image_tool.find_target(end_sign) is not None:
            break


def move_to(target_image, offset_x, offset_y, duration):
    target_loc = image_tool.find_target(target_image)
    if target_loc is None:
        return
    target_x, target_y = target_loc
    ac.reset_actions()
    ac.move_by_offset(target_x + offset_x, target_y + offset_y).click_and_hold().perform()
    time.sleep(duration)
    ac.release().perform()


def make_rope(action, tex_loc):
    tex_x, tex_y = tex_loc
    action.click_by_offset(tex_x - 120, tex_y + 220)
    time.sleep(0.5)
    cooking_item_name = 'Rack of Rope'
    opt = action.find_element(By.XPATH, f"//span[text()='{cooking_item_name}']", cooking_item_name, 3)
    if opt is None:
        action.escape()
        time.sleep(1)
        action.click()
        opt = action.find_element(By.XPATH, f"//span[text()='{cooking_item_name}']", cooking_item_name, 10)
    opt.click()
    time.sleep(1)

    craft_button = action.find_element(By.CLASS_NAME, "Crafting_craftingButton__Qd6Ke", 'CraftButton', 2)
    if craft_button.text == 'Create':
        if craft_button.is_enabled():
            craft_button.click()
    time.sleep(0.5)
    action.escape()
    time.sleep(0.5)


if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Silk_Slug_3450')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    log = Log(user_id)
    driver = AdsWindow(user_id).open(False)
    game = Game(driver, user_id)
    action = WebDriverAction(driver, user_id=user_id)
    movement = Movement(driver)
    image_tool = ImageTool(driver)
    trade_helper = TradeHelper(driver, user_id)
    ac = ActionChains(driver)
    slug_name = 'Silk Slug'
    need_slug = False

    try:
        game.enter_game()
        game.collect_mail()
        snapshot = game.snapshot(user_id, 'before slug')
        skills = snapshot.get('skills')
        business_level = skills.get('business', 0)
        log.debug(f'business_level={business_level}')

        slug_index, _ = game.get_backpack_index_and_qty(slug_name)
        min_energy = 820

        action.goto_spec()
        if game.get_energy() < min_energy:
            game.snapshot(user_id, 'after slug', include_skills=False)
            task_helper.task_fail()
        else:
            action.goto_land(3450)
            movement.keep_move_up(2.7)
            move_and_collect()

            try:
                log.debug('throw silk_fiber')
                dustbin_image = 'dustbin.png'
                action.move_to(dustbin_image, max_loop=3)
                time.sleep(1)
                dustbin_loc = image_tool.find_target(dustbin_image)
                dustbin_x, dustbin_y = dustbin_loc
                if business_level >= 8:
                    game.chest_in(dustbin_x, dustbin_y, ['Silk Fiber'], {"Silk Fiber": 72})
                else:
                    game.chest_in(dustbin_x, dustbin_y, ['Silk Fiber'])
            except Exception as e:
                log.debug('throw silk_fiber failed')
                print(e)

            try:
                action.goto_terra()
                slime_name = 'Silk Slug Slime'
                if business_level >= 8:
                    # 做Silk Rope
                    tex_loc = action.goto_textile_station()
                    make_rope(action, tex_loc)
                    action.goto_spec()
                trade_helper.goto_sell_position()
                trade_helper.open_shop_sell()
                # 做完仍有剩余去卖掉
                if business_level >= 8:
                    if game.get_backpack_qty(slime_name) > 99:
                        trade_helper.sell_item(slime_name, 9999)
                else:
                    trade_helper.sell_item(slime_name, 9999)
                # trade_helper.sell_item('Silk Fiber', 9999)
                trade_helper.sell_item('Silk Slug Spider', 9999, price_delta=-1)
                trade_helper.sell_item('Silk Rope', 9999)
                action.escape()
                action.escape()

            except Exception as e:
                print(e)
                pass
            try:
                if need_slug:
                    trade_helper.goto_buy_position()
                    filter_input = trade_helper.open_market_buy()
                    buy_qty = min(80, int(game.get_coin() / 1000))
                    trade_helper.market_buy_item(filter_input, slug_name, buy_qty)
                    action.escape()
                    action.escape()
            except Exception as e:
                print(e)
        game.snapshot(user_id, 'after slug', include_skills=False)
        task_helper.task_success()
    except Exception as e:
        task_helper.task_fail()
        task_helper.silk_slug(3450, retry=True)
        raise e
